#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  char ch;
  int cnt;
} char_cnt_t;

static int get_char_location(char ch, char_cnt_t *ch_set, int set_size) {
  int i;
  int index = -1;
  for (i = 0; i < set_size; i++) {
    if (ch == ch_set->ch) {
      index = i;
      break;
    }
    ch_set++;
  }
  return index;
}
int cmp_char_cnt(const void *key1, const void *key2) {
  const char_cnt_t *p1, *p2;
  p1 = key1;
  p2 = key2;
  if (p1->cnt > p2->cnt) {
    return 1;
  } else if (p1->cnt == p2->cnt) {
    return 0;
  } else {
    return -1;
  }
}

int issort(void *data, int size, int esize,
           int (*compare)(const void *key1, const void *key2)) {
  char *p = data;
  void *key;
  int i, j;
  if (NULL == (key = malloc(esize))) {
    return -1;
  }
  for (i = 1; i < size; i++) {
    memcpy(key, &p[i * esize], esize);
    j = i - 1;
    while (j >= 0 && (-1 == compare(key, &p[j * esize]))) {
      memcpy(&p[(j + 1) * esize], &p[j * esize], esize);
      j--;
    }
    memcpy(&p[(j + 1) * esize], key, esize);
  }
  free(key);
  return 0;
}

char *delete_char_appear_least(char *str) {
  char_cnt_t counter[26 * 2] = {0};
  int repeated_ch_location;
  int ch_diff_cnt = 0;
  int str_len = 0;
  char *p_index = str;
  str_len = strlen(str);
  for (int i = 0; i < str_len; i++) {
    repeated_ch_location = get_char_location(*p_index, counter, ch_diff_cnt);
    if (-1 == repeated_ch_location) {
      counter[ch_diff_cnt].ch = *p_index;
      counter[ch_diff_cnt].cnt += 1;
      ch_diff_cnt++;
    } else {
      counter[repeated_ch_location].cnt++;
    }
  }
}
